package com.eclipse.e20200201_多线程同步.多线程基础语法;

import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class Test1 {

	public static void main(String[] args) {
//		处理线程run()抛出的异常
//		Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
//			public void uncaughtException(Thread t, Throwable e) {
//				System.out.println(t.getName() + ":" + e.getClass());
//			}
//		});
		try {
			Task1 task1 = new Task1("/Users/liuzhuangzhuang/iotest/a.txt");
			
			task1.setName("task1....");
//			task1.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
//				public void uncaughtException(Thread t, Throwable e) {
//					System.out.println(t.getName() + ":" + e.getMessage());
//				}
//			});
			// 这是普通的方法调用
			// task1.run();
			// 启动线程
			task1.start();
			task1.join();
		}catch (InterruptedException e) {
				e.printStackTrace();
			
		} catch (NullPointerException ex) {
			System.out.println("---------------------");
			ex.printStackTrace();
		}

		/*
		 * try { task1.join(); } catch (InterruptedException e) { // TODO Auto-generated
		 * catch block e.printStackTrace(); }
		 */

		Task3 task3 = new Task3();
		Thread thread3 = new Thread(task3);
		thread3.setName("task3....");
//		System.out.println(Thread.currentThread().getName());

		// 守护线程，不管是否运行完成，只要没有其他非守护线程，进程就会退出 
		// thread3.setDaemon(true);
		thread3.start();

//		Task1 task2 = new Task1("/Users/liuzhuangzhuang/iotest/a.txt");
//		task2.setName("task2....");
//		task2.start();

		/*
		 * Thread thread3 = new Thread(new Runnable() { public void run() { for (int i =
		 * 0; i < 10; i++) { System.out.println(i); } } });
		 * 
		 * thread3.setName("task3...."); thread3.start();
		 */
	}

}

//2:实现Runnable接口
class Task3 implements Runnable {
	public void run() {
		
		for (int i = 0; i < 10; i++) {
			System.out.println(Thread.currentThread().getName() + ":" + i);
//			System.out.println("线程3:"+i);
//			try {
//				Thread.currentThread().sleep(1000);
//				
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}

		}
	}
}

//1: 继承Thread
class Task1 extends Thread {
	private String fileName;

	public Task1(String fileName) {
		this.fileName = fileName;
	}

	// 重写run方法
	public void run() {
		
		try {
			List<String> lines = Files.readAllLines(Paths.get(fileName));
			// 让出CPU的使用权
//			super.yield();
			super.setName("qwe");
			
			for (String line : lines) {
				System.out.println(super.getName() + ":" + line);
			}
			String str = null;
			str.chars();
		} catch (Exception e) {
			System.out.println("Exception............");
			e.getClass();//获取异常类型
			e.getMessage();//获取描述信息
			e.printStackTrace();
		}
	}
}
